package com.demo.entity.riot;

import com.demo.service.riot.RegionTransfer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MatchInfo {
    private String matchId;
    private Long gameCreation;
    private Integer gameDuration;
    private String gameMode;
    private String gameType;
    private String gameVersion;
    private Integer mapId;
    private String platformId;
    private Integer queueId;
    private String dataVersion;
    private String rawJson; // 完整JSON用于AI分析

    private ObjectMapper objectMapper = new ObjectMapper();

    public String getMatchId() {
        return matchId;
    }

    public void setMatchId(String matchId) {
        this.matchId = matchId;
    }

    public Long getGameCreation() {
        return gameCreation;
    }

    public void setGameCreation(Long gameCreation) {
        this.gameCreation = gameCreation;
    }

    public Integer getGameDuration() {
        return gameDuration;
    }

    public void setGameDuration(Integer gameDuration) {
        this.gameDuration = gameDuration;
    }

    public String getGameMode() {
        return gameMode;
    }

    public void setGameMode(String gameMode) {
        this.gameMode = gameMode;
    }

    public String getGameType() {
        return gameType;
    }

    public void setGameType(String gameType) {
        this.gameType = gameType;
    }

    public String getGameVersion() {
        return gameVersion;
    }

    public void setGameVersion(String gameVersion) {
        this.gameVersion = gameVersion;
    }

    public Integer getMapId() {
        return mapId;
    }

    public void setMapId(Integer mapId) {
        this.mapId = mapId;
    }

    public String getPlatformId() {
        return platformId;
    }

    public void setPlatformId(String platformId) {
        this.platformId = platformId;
    }

    public Integer getQueueId() {
        return queueId;
    }

    public void setQueueId(Integer queueId) {
        this.queueId = queueId;
    }

    public String getDataVersion() {
        return dataVersion;
    }

    public void setDataVersion(String dataVersion) {
        this.dataVersion = dataVersion;
    }

    public String getRawJson() {
        return rawJson;
    }

    public void setRawJson(String rawJson) {
        this.rawJson = rawJson;
    }

    public MatchInfo() {

    }

    /**
     * 根据召唤师技能id转换为对应的英文名id
     * @param id 召唤师技能的数字id
     * @return 对应的英文名id
     * @throws IOException
     */
    public String TransformSummoner(Integer id) throws IOException {
        ClassPathResource resource = new ClassPathResource("static/summoner.json");
        try (InputStream inputStream = resource.getInputStream()) {
            JsonNode jsonNode = objectMapper.readTree(inputStream);
            JsonNode datas = jsonNode.path("data");
            for (JsonNode data : datas) {
                String currentKey = data.get("key").asText();
                if (currentKey.equals(id.toString())) {
                    return data.get("id").asText();
                }
            }
        }
        return null;
    }

    /**
     * 按队伍把玩家装入Json中，用于概览展示
     * @param root 对局信息的根Json文件
     * @return
     */
    public JsonNode getTeamNode(JsonNode root){
        JsonNode participants = root.path("info").path("participants");
        ArrayNode teams = objectMapper.createArrayNode();
        ObjectNode team1 = objectMapper.createObjectNode();
        ObjectNode team2 = objectMapper.createObjectNode();
        ArrayNode members1 = objectMapper.createArrayNode();
        ArrayNode members2 = objectMapper.createArrayNode();
        for(int i = 0; i < participants.size(); i++) {
            JsonNode participant = participants.get(i);
            if(participant.path("teamId").asInt() == 0) {
                team1.put("teamId", 0);
                team2.put("teamId", 100);
                break;
            } else if(participant.path("teamId").asInt() == 200) {
                team1.put("teamId", 100);
                team2.put("teamId", 200);
                break;
            }
        }

        for(JsonNode participant : participants){
            ObjectNode member =  objectMapper.createObjectNode();
            member.put(participant.get("riotIdGameName").asText(), participant.get("championName").asText());
            if(participant.path("teamId").asInt() == team1.get("teamId").asInt()) {
                members1.add(member);
            } else{
                members2.add(member);
            }
        }
        team1.put("members", members1);
        team2.put("members", members2);
        teams.add(team1).add(team2);
        JsonNode teamsNode = teams;
        return teamsNode;
    }

    // 在参与者数组中查找特定玩家的节点
    public JsonNode findParticipant(JsonNode root, String puuid) {
        JsonNode participants = root.path("info").path("participants");
        for (JsonNode participant : participants) {
            if (puuid.equals(participant.path("puuid").asText())) {
                return participant;
            }
        }
        return null;
    }

    public List<Summoner> toSummoners() {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode root = objectMapper.readTree(this.rawJson);
            JsonNode info = root.path("info");
            JsonNode participants = info.path("participants");
            List<Summoner> summoners = new ArrayList<>();
            for(JsonNode summonerNode : participants) {
                Summoner summoner = new Summoner();
                summoner.setPuuid(summonerNode.path("puuid").asText());
                summoner.setServerRegion(info.path("platformId").asText().toLowerCase());
                summoner.setRegion(RegionTransfer.getRegion(summoner.getServerRegion()));
                summoner.setGameName(summonerNode.path("riotIdGameName").asText());
                summoner.setTagLine(summonerNode.path("riotIdTagline").asText());
                summoner.setProfileIconId(summonerNode.path("profileIcon").asText());
                summoner.setSummonerLevel(summonerNode.path("summonerLevel").asInt());
                summoners.add(summoner);
            }
            return summoners;
        }  catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to parse summoner JSON for match " + this.matchId, e);
        }
    }

    // 辅助方法：通过puuid查找参与者
    private JsonNode findParticipantByPuuid(JsonNode infoNode, String puuid) {
        JsonNode participants = infoNode.path("participants");
        for (JsonNode participant : participants) {
            if (puuid.equals(participant.path("puuid").asText())) {
                return participant;
            }
        }
        return null;
    }

    public JsonNode getPerks(JsonNode participantNode){
        ObjectNode perks = objectMapper.createObjectNode();
        JsonNode fullPerks = participantNode.path("perks").path("styles");
        for (JsonNode perk : fullPerks) {
            if(perk.get("description").asText().equals("primaryStyle")){
                perks.put("primaryPerk", perk.path("selections").get(0).get("perk").asInt());
            } else {
                perks.put("subStyle", perk.path("style").asInt());
            }
        }
        return perks;
    }

    // 创建目标对象
    public MatchTeam.Objective createObjective(JsonNode objectiveNode) {
        MatchTeam.Objective objective = new MatchTeam.Objective();
        objective.setFirst(objectiveNode.path("first").asBoolean());
        objective.setKills(objectiveNode.path("kills").asInt());
        return objective;
    }
}
